package cc.magicjson.mall.member.domain.model;

import cc.magicjson.mall.common.domain.AggregateRoot;
import cc.magicjson.mall.common.domain.DomainEvent;
import cc.magicjson.mall.common.util.IdGenerator;
import cc.magicjson.mall.member.domain.event.MemberRegisteredEvent;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Getter
public class MemberAggregate implements AggregateRoot<String> {
	private String id;
	private final Member member;
	// 注意：实际应用中应该加密存储
	private MemberStatus status;
	private final List<DomainEvent> domainEvents = new ArrayList<>();

	public MemberAggregate(Member member) {
		this.id = IdGenerator.generateId();
		this.member = member;
		this.status = MemberStatus.ACTIVE;
		this.domainEvents.add(new MemberRegisteredEvent(member));
	}

	public void deactivate() {
		if (this.status != MemberStatus.ACTIVE) {
			throw new IllegalStateException("Member is not active");
		}
		this.status = MemberStatus.INACTIVE;
	}

	public void suspend() {
		if (this.status == MemberStatus.SUSPENDED) {
			throw new IllegalStateException("Member is already suspended");
		}
		this.status = MemberStatus.SUSPENDED;
	}

	public void activate() {
		if (this.status == MemberStatus.ACTIVE) {
			throw new IllegalStateException("Member is already active");
		}
		this.status = MemberStatus.ACTIVE;
	}

	public void markAsDeleted() {
		this.status = MemberStatus.DELETED;
	}

	@Override
	public String getId() {
		return id;
	}

	public List<DomainEvent> getDomainEvents() {
		return Collections.unmodifiableList(domainEvents);
	}

	public void clearDomainEvents() {
		this.domainEvents.clear();
	}
}